package com.product.controler;


import com.product.pojo.Product;
import com.product.service.ProductService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    // 添加商品
    @PostMapping
    public ResponseEntity<Product> addProduct(@RequestBody Product product) {
        Product addedProduct = productService.addProduct(product);
        return new ResponseEntity<>(addedProduct, HttpStatus.CREATED);
    }

    // 更新商品信息
    @PutMapping
    public ResponseEntity<Product> updateProduct(@RequestBody Product product) {
        Product updatedProduct = productService.updateProduct(product);
        return new ResponseEntity<>(updatedProduct, HttpStatus.OK);
    }

    // 删除商品
    @DeleteMapping("/{productId}")
    public ResponseEntity<Void> deleteProduct(@PathVariable String productId) {
        productService.deleteProduct(productId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    // 根据商品ID获取商品信息
    @GetMapping("/{productId}")
    public ResponseEntity<Product> getProductById(@PathVariable String productId) {
        Product product = productService.getProductById(productId);
        if (product!= null) {
            return new ResponseEntity<>(product, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    // 获取所有商品列表
    @GetMapping
    public ResponseEntity<List<Product>> listAllProducts() {
        List<Product> products = productService.listAllProducts();
        return new ResponseEntity<>(products, HttpStatus.OK);
    }

    // 根据分类获取商品列表
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<List<Product>> listProductsByCategory(@PathVariable String categoryId) {
        List<Product> products = productService.listProductsByCategory(categoryId);
        return new ResponseEntity<>(products, HttpStatus.OK);
    }

    // 商品上架
    @PutMapping("/{productId}/on-shelf")
    public ResponseEntity<Void> onShelf(@PathVariable String productId) {
        productService.onShelf(productId);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    // 商品下架
    @PutMapping("/{productId}/off-shelf")
    public ResponseEntity<Void> offShelf(@PathVariable String productId) {
        productService.offShelf(productId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}